package com.chrudgames.stayintouch;

import java.text.SimpleDateFormat;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.util.Log;


public class AlarmReceiverActivity extends  Activity {
    
	boolean SMS = true;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Log.d("SIT","alarm receiver");
   
        SharedPreferences prefs = PreferenceManager
                            .getDefaultSharedPreferences(getBaseContext());
        
        if(prefs.getBoolean("pref_sms", false)){
        	SMS = false;
        }
        
        if(prefs.getBoolean("pref_notify", true)){
         
        		updateDays();
           		findOutofTouch();;
        
        }
        
       finish();
        
    }
 
public void sendNotify(String strName) {
    	
    	String ns = Context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	
    	int icon = R.drawable.stayintouchicongrey;
    	CharSequence tickerText = "Out of Touch";
    	long when = System.currentTimeMillis();

    	Notification notification = new Notification(icon, tickerText, when);
    	
    	Context context = getApplicationContext();
    	CharSequence contentTitle = "Out of Touch";
    	CharSequence contentText = "Out of Touch with " + strName;
    	Intent notificationIntent = new Intent(this, StayInTouchActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    	notification.flags = Notification.DEFAULT_LIGHTS | Notification.FLAG_AUTO_CANCEL;
    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    	
    	final int HELLO_ID = 1;

    	mNotificationManager.notify(HELLO_ID, notification);
    	
    }

public void updateDays(){
	
	//try {
	
    String lookupKey = "";
    String tmpPhone = "";
    String phoneNumbers = "";
    String strName = "";
    String DurationPreference = "";


	SharedPreferences prefs = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());
    
	DurationPreference = prefs.getString("pref_duration", "60");
	if(DurationPreference.length()<1){DurationPreference="0";}
    
	String[] projection = { "date", "duration", "type" };
	String selection = "duration>" + DurationPreference;
	String selectionArgs[] = null;// phoneNumbers;
	String sortOrder = android.provider.CallLog.Calls.DATE + " DESC";
	
	SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 

	DatabaseHandler db = new DatabaseHandler(this);
    Cursor contacts = (Cursor) db.getAllContactsCursor();
    
    while (contacts.moveToNext()) { 
    
    	
    	
    	
    	if (contacts.getString(0).equalsIgnoreCase(db.getID().toString())) {
    	
    	}else{	

    		
    	    lookupKey = contacts.getString(0);    
	        
    	    
	    	Uri lookupUri = Uri.withAppendedPath(Contacts.CONTENT_LOOKUP_URI, lookupKey);

	   		    	
	    	Cursor c = getContentResolver().query(lookupUri, new String[]{Contacts.DISPLAY_NAME, Contacts.LAST_TIME_CONTACTED, Contacts.HAS_PHONE_NUMBER},null, null, null);
	    
	    	if (c.getCount()==0){ 
	    		Log.d("Error", "Count=0");
	    		phoneNumbers="";
	    		db.runQuery("delete from contacts where _id='" + lookupKey + "'");
	    		//alertbox(mContext.getString(R.string.Missing_Contact), contacts.getString(3) + "\u0020" + mContext.getString(R.string.is_no_longer_in));
	    	}else{
	    	
	    	
	    	    c.moveToFirst();
  	    		    	    
 	           String hasPhone = c.getString(2);
 	           strName =  c.getString(0);
 	           strName = strName.replace("'", "''");
 	           
	           if (hasPhone.contains("1")) { 
	        	   
	            Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.LOOKUP_KEY +" = '" + lookupKey + "'", null, null);  
	      	      while (phones.moveToNext()) { 
	      	    	  
	      	    	tmpPhone = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));  
	      	    	tmpPhone = tmpPhone.replaceAll("[^0-9]","");
	      	    	
	      	    	if(tmpPhone.length()>6){tmpPhone = tmpPhone.substring(tmpPhone.length() - 6);}
	      	    	
	      	        phoneNumbers = phoneNumbers + "'" + tmpPhone + "',";	      	        
	      	      
	      	      } 
	      	   phones.close(); 
	      	   
	      	// Log.w("onActivityResult", "Phones: " + c.getString(0).toString() + phoneNumbers);     
	      	   
	      	if(phoneNumbers.length()>1){  phoneNumbers = phoneNumbers.substring(0, phoneNumbers.length() - 1);}

	           }
	      	}
	            
	            
	    	
	    	    c.close();
	    	
	    	
	    	    
	    	
	    	selection = "duration>" + DurationPreference + " and substr(replace(number, '-',''),-6,6) IN (" + phoneNumbers + ")";

		    	Cursor calldate = null;

		    		Long datLatest = null;

		          
		           calldate = getContentResolver().query(
		    	            Uri.parse("content://call_log/calls"),
		    	            projection,
		    	            selection,
		    	            selectionArgs,
		    	            sortOrder);
		            
		           
		           if (calldate.moveToFirst()) {
		              
		        	   datLatest = calldate.getLong(0);


		           }
		            
		           calldate.close();
	    	
		           
		            
			    	selection = "substr(replace(address, '-',''),-6,6) IN (" + phoneNumbers + ")";//  "person='" + lookupKey +"'";
			    	c = null;
			    	
			    	
			    	if(SMS==true){
			        
			           c = getContentResolver().query(
			    	            Uri.parse("content://sms/sent"),
			    	            null,
			    	            selection,
			    	            selectionArgs,
			    	            null);
			           
			
			            
				           if (c.moveToFirst()) {
					              
				        	if(datLatest<c.getLong(c.getColumnIndex("date"))) datLatest = c.getLong(c.getColumnIndex("date"));
				        	
			        	   				            
			    		
			    	}
				         
				           
				           c = getContentResolver().query(
				    	            Uri.parse("content://sms/inbox"),
				    	            null,
				    	            selection,
				    	            selectionArgs,
				    	            null);
				           
				
				            
					           if (c.moveToFirst()) {
						              
					        	   if(datLatest<c.getLong(c.getColumnIndex("date"))) datLatest = c.getLong(c.getColumnIndex("date"));

					       
				    	}
					                      
				       		        
			    	//}catch(Exception ex){
			    	//	Log.w("SIT",ex.getMessage().toString());
			    	//}finally{
			    	   c.close();
			    	//}
			    	
			    	   
		           
	    	}
		           
		           
		           phoneNumbers = "";
		           
		           if(datLatest!=null){
		        	   

		        	   db.runQuery("update contacts set last = '" + dateFormat.format(datLatest) + "', name='" + strName + "' where _id='" + lookupKey.toString() + "' and " +
		        	   		" datetime(last) < Datetime('" + dateFormat.format(datLatest) + "')");
		        	   
		        	   
		           }
		           
		    	   //db.close();
    		}   
		           
	         }
    
    contacts.close();
    db.close();
	
	//} catch (Exception e) {
		
//		Log.d("SIT",  "error=" + e.getMessage());
		
//	}
    
}


public void findOutofTouch(){
	

	DatabaseHandler db = new DatabaseHandler(this);
    Cursor contacts = (Cursor) db.getAllDueContactsCursor();
    
    
    
    if(contacts.moveToFirst()){
    	
    	if(contacts.getCount()==1){
    		
    		sendNotify("with " + contacts.getString(0));
    		
    	}else{
    	    	
    		sendNotify( contacts.getCount() + " contacts");  
    	    
    	}  
    	
    }
    
  contacts.close();  
  db.close();

    
}


}